package org.cainiao.basic.reference;

import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.TimeUnit;

import static org.cainiao.util.Util.log;

/**
 * <br />
 * <p>
 * Author: Cai Niao(wdhlzd@163.com)<br />
 */
public class ReferenceTest {

    public static void main(String[] args) throws InterruptedException {
        testWeakHashMap();
    }

    private static void testWeakHashMap() throws InterruptedException {
        WeakHashMap<Object, String> weakHashMap = new WeakHashMap<>();
        Object o2 = new Object();
        weakHashMap.put(o2, "abc");

        log("weakHashMap.entrySet()", weakHashMap.entrySet());
        for (Map.Entry<Object, String> entry : weakHashMap.entrySet()) {
            log("entry", entry);
            log("entry.getKey()", entry.getKey());
            log("entry.getValue()", entry.getValue());
        }

        Object o = new Object();
        WeakReference<Object> weakReference = new WeakReference<>(o);
        
        log("weakReference.get()", weakReference.get());

        o = null;
        o2 = null;
        for (int i = 0; i < 5; i++) {
            log("i", i);
            System.gc();
            TimeUnit.SECONDS.sleep(1);
        }
        log("weakReference.get()", weakReference.get());
        log("weakReference", weakReference);

        log("weakHashMap.entrySet()", weakHashMap.entrySet());
        for (Map.Entry<Object, String> entry : weakHashMap.entrySet()) {
            log("entry", entry);
            log("entry.getKey()", entry.getKey());
            log("entry.getValue()", entry.getValue());
        }
    }

    private static void testWeakReference() throws InterruptedException {
        Object o = new Object();
        WeakReference<Object> weakReference = new WeakReference<>(o);
        log("weakReference.get()", weakReference.get());
        o = null;
        for (int i = 0; i < 5; i++) {
            log("i", i);
            System.gc();
            TimeUnit.SECONDS.sleep(1);
        }
        log("weakReference.get()", weakReference.get());
        log("weakReference.get()", weakReference);
    }
}
